/*
 * @(#)RequestParser.java
 *
 */

package diablo3.socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import diablo3.support.Util;

/**
 * description
 * @author  huangyixiang
 * @version 2012-12-14
 */
public class RequestParser {
	
	private static final Log LOG = LogFactory.getLog(RequestParser.class);
	
	/**
	 * 传入HTTP请求中需要解析的某一句 解析该句，并请放入对应的Request对象中
	 * 
	 * @param s
	 */
	public Request parser(String s) {
		Request request = new Request();
		for(String line : s.split("\\r\\n")){
			if(Util.isBlank(line)){
				continue;
			}
			parseLine(request, line);
		}
		
		return request;
	}
	
	private void parseLine(Request request, String s){
		if (s.startsWith("GET")) {
			String method = "Get";
			request.setMethod(method);

			int index = s.indexOf("HTTP");
			LOG.info("index--->" + index);
			String uri = s.substring(3 + 1, index - 1);// 用index-1可以去掉连接中的空格
			LOG.info("uri--->" + uri);
			request.setRequestURI(uri);

			String protocol = s.substring(index);
			LOG.info("protocol---->" + protocol);
			request.setProtocol(protocol);
		} else if (s.startsWith("POST")) {
			String method = "POST";
			request.setMethod(method);

			int index = s.indexOf("HTTP");
			LOG.info("index--->" + index);
			String uri = s.substring(3 + 1, index - 1);// 用index-1可以去掉连接中的空格
			LOG.info("uri--->" + uri);
			request.setRequestURI(uri);

			String protocol = s.substring(index);
			LOG.info("protocol---->" + protocol);
			request.setProtocol(protocol);

		} else if (s.startsWith("Accept:")) {
			String accept = s.substring("Accept:".length() + 1);
			LOG.info("accept--->" + accept);
			request.setAccept(accept);

		} else if (s.startsWith("User-Agent:")) {
			String agent = s.substring("User-Agent:".length() + 1);
			LOG.info("agent--->" + agent);
			request.setAgent(agent);

		} else if (s.startsWith("Host:")) {
			String host = s.substring("Host:".length() + 1);
			LOG.info("host--->" + host);
			request.setHost(host);

		} else if (s.startsWith("Accept-Language:")) {
			String language = s.substring("Accept-Language:".length() + 1);
			LOG.info("language--->" + language);
			request.setLanguage(language);

		} else if (s.startsWith("Accept-Charset:")) {
			String charset = s.substring("Accept-Charset:".length() + 1);
			LOG.info("charset--->" + charset);
			request.setCharset(charset);
		} else if (s.startsWith("Accept-Encoding:")) {
			String encoding = s.substring("Accept-Encoding:".length() + 1);
			LOG.info("encoding--->" + encoding);
			request.setEncoding(encoding);

		} else if (s.startsWith("Connection:")) {
			String connection = s.substring("Connection:".length() + 1);
			LOG.info("connection--->" + connection);
			request.setConnection(connection);
		}
	}
	

}
